import { EventSubscriber, On } from 'event-dispatch';
import Container from 'typedi';
import { logger } from '../common/logger';
import { UserService } from '../services/UserService';

@EventSubscriber()
export class UserSubscriber {

    userService: UserService = Container.get(UserService);

    @On('login')
    onLogin({ socket }) {
        logger.info(`Socker ${socket.id} onLogin`);

        this.userService.usocket[socket.id] = socket;

        // do something

        return true;
    }

    @On('disconnect')
    disconnect({ socket, req }) {
        logger.info(`Socker ${socket.id} disconnect, reason: ${req}`);

        // 移除socket
        if (socket.id in this.userService.usocket) {
            delete (this.userService.usocket[socket.id]);
        }
    }
}
